class Subject {
    declare private _observers: Observer[]
    constructor() {
        console.log('调用subject的构造');
        this._observers = []
    }
    attach(observer: Observer) {
        this._observers.push(observer)
    }
    detach(observer: Observer) {
        this._observers = this._observers.filter(o => o !== observer);
    }
    notify() {
        for (let i = 0; i < this._observers.length; i++) {
            this._observers[i].update(this)
        }
    }

}
interface Observer {
    update(subject: Subject): void
}

class ClockTimer extends Subject {
    constructor() {
        super()
        setInterval(() => { this.tick() }, 1000)//此处使用箭头函数，不然this指向会变化
    }

    getHour(): number {
        return new Date().getHours()
    }
    getMinute(): number {
        return new Date().getMinutes()
    }
    getSecond(): number {
        return new Date().getSeconds()
    }
    //内部定时器调用
    tick() {
        super.notify();
    }
}
class DigitalClock implements Observer {
    private declare _timer: ClockTimer
    constructor(timer: ClockTimer) {
        this._timer = timer
        this._timer.attach(this)
    }
    update(subject: Subject): void {
        if (subject === this._timer) {
            this.draw()
        }
    }
    draw() {
        console.log(`画时钟=>${this._timer.getHour()}:${this._timer.getMinute()}:${this._timer.getSecond()}`);
    }

}
const timer = new ClockTimer()
const digitalClock = new DigitalClock(timer)